import {mapMutations} from 'vuex';
import store from '@/store';

const common = {
  fileServer(imagePath) {
    if (!imagePath) {
      return '';
    }
    if (imagePath.indexOf('https') === 0 || imagePath.indexOf('http') === 0) {
      return imagePath;
    }
    const nfsAddress = store.getters.getNfsAddress;
    const src = `${nfsAddress}${imagePath}`;

    return src;
  },
  getUrlParam: function (url, name) {
    if (!url) return null;
    console.log('url', typeof url);
    var param = url.split('?')[1];
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)'); // 构造一个含有目标参数的正则表达式对象
    var r = param.match(reg); // 匹配目标参数
    if (r != null) return unescape(r[2]);
    return null; // 返回参数值
  },
  /**
   * @func 获取当前页面的路由url
   * @return 返回当前页面的路由
   */
  getCurrRouter() {
    const pages = getCurrentPages();
    let currPage = {};
    if (pages.length) {
      currPage = pages[pages.length - 1];
    }
    return currPage.route;
  },
};

const mixins = {
  data() {
    return {};
  },
  onLoad(option) {
    console.log('option:', option);

    if (this._token) {
      if (Object.isFunction(this.onLoginSuccess)) {
        this.getUserdata().then(() => {
          this.onLoginSuccess(option);
        });
      }
    } else {
      if (Object.isFunction(this.onLoginSuccess)) {
        this.loadAppLaunch().then(() => {
          this.onLoginSuccess(option);
        });
      }
    }
  },

  filters: {
    fileServer(imagePath) {
      return common.fileServer(imagePath);
    },
  },
  computed: {
    userInfo() {
      if (!this.$store) {
        return {};
      }
      return this.$store.getters.getUserInfo;
    },
    _token() {
      if (!this.$store) {
        return '';
      }
      return this.$store.getters.token;
    },
    _openId() {
      if (!this.$store) {
        return '';
      }
      return this.$store.getters.openId;
    },
  },
  watch: {},
  methods: {
    ...mapMutations(['refreshToken', 'refreshUserInfo', 'refreshOpenId']),
    fileServer(imagePath) {
      return common.fileServer(imagePath);
    },
    // 路由拦截是否登录

    // 提前获取用户授权请求
    getUserSetting(scope) {
      if (String.isEmpty(scope)) return;
      return new Promise((resolve, reject) => {
        let msg = '';
        switch (scope) {
          case 'scope.writePhotosAlbum':
            msg = '保存到相册';
            break;
          case 'scope.invoice':
            msg = '获取发票';
            break;
          case 'scope.address':
            msg = '通讯地址';
            break;
          case 'scope.userInfo':
            msg = '用户信息';
            break;
        }
        uni.getSetting({
          success(res) {
            if (!res.authSetting[scope]) {
              uni.authorize({
                scope,
                success() {
                  resolve('success');
                },
                fail() {
                  uni.showModal({
                    content: `检测到您没“${msg}”功能权限，是否去设置打开？`,
                    confirmText: '确认',
                    cancelText: '取消',
                    success: function (res) {
                      if (res.confirm) {
                        wx.openSetting({
                          success: (res) => {},
                        });
                      } else {
                        console.log('用户点击取消');
                      }
                    },
                  });
                },
              });
            } else {
              resolve('success');
            }
          },
          fail(err) {
            reject(err);
          },
        });
      });
    },
    getUrlParam(url, name) {
      return common.getUrlParam(url, name);
    },
    loadAppLaunch() {
      return new Promise((resolve) => {
        const _this = this;
        uni.login({
          provider: 'weixin',
          success(loginRes) {
            _this.getUserInfo(loginRes.code).then((openId) => {
              resolve(openId);
            });
          },
          fail(err) {
            console.log('调用登录接口失败', err);
          },
        });
      });
    },
    // 获取授权信息
    getUserInfo(code) {
      return new Promise((resolve, reject) => {
        const _this = this;
        uni.getSetting({
          success(res) {
            if (res.authSetting['scope.userInfo']) {
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称
              uni.getUserInfo({
                provider: 'weixin',
                success(infoRes) {
                  console.log(infoRes);

                  const param = {
                    code,
                    userEncryptedData: infoRes.encryptedData,
                    userIv: infoRes.iv,
                  };
                  _this.wxPhone(param).then((openid) => {
                    resolve(openid);
                  });
                },
              });
            } else {
              uni.reLaunch({
                url: '/pages/logged/authorize/authorize',
              });
              reject();
            }
          },
        });
      });
    },
    // 登录
    wxPhone(param) {
      return new Promise((resolve) => {
        this.$api.auth.wxlogin(param).then((res) => {
          this.refreshOpenId(res.openid);
          uni.reLaunch({
            url: '/pages/logged/login/login',
          });
          resolve(res.openid);
        });
      });
    },
    // 获取用户信息
    getUserdata() {
      return new Promise((resolve) => {
        const param = {token: this._token, openId: this._openId};
        this.$api.auth.userdata(param).then((result) => {
          this.refreshUserInfo(result);
          resolve();
        });
      });
    },
  },
};

export default mixins;
